package com.chenglu.android.restaurant.shop.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.cart.bean.CartBean;
import com.chenglu.android.common.base.BaseMvpFragment;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.PxUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.index.BannerUtils;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.restaurant.adapter.ShopCategoryAdapter;
import com.chenglu.android.restaurant.adapter.ShopCategoryGoodItemAdapter;
import com.chenglu.android.restaurant.bean.CurrentShopsInfoBean;
import com.chenglu.android.restaurant.bean.GoodscategorylisBean;
import com.chenglu.android.restaurant.bean.ReviewTypeCountBean;
import com.chenglu.android.restaurant.bean.ShopReviewPageBean;
import com.chenglu.android.restaurant.event.ReviewTypeCountEvent;
import com.chenglu.android.restaurant.mvp.contract.RestaurantShopContract;
import com.chenglu.android.restaurant.mvp.presenter.RestaurantShopPresenter;
import com.chenglu.android.restaurant.shop.details.ShopDetailsActivity;
import com.chenglu.android.restaurant.shop.sku.ProductSkuDialog;
import com.chenglu.android.restaurant.shop.sku.bean.ProductData;
import com.chenglu.android.restaurant.shop.sku.bean.Sku;
import com.chenglu.android.restaurant.shop.sku.bean.SkuAttribute;
import com.chenglu.android.restaurant.shop.view.CenterLayoutManager;
import com.chenglu.android.restaurant.shop.view.CustomScrollView;
import com.gavin.com.library.PowerfulStickyDecoration;
import com.gavin.com.library.listener.PowerGroupListener;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MenuScrollFragment extends BaseMvpFragment<RestaurantShopPresenter> implements RestaurantShopContract.View {


    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.cv_shop_menu)
    CardView cvShopMenu;
    @BindView(R.id.rv_left)
    RecyclerView rvLeft;
    @BindView(R.id.rv_right)
    RecyclerView rvRight;
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.scrollView)
    CustomScrollView scrollView;
    @BindView(R.id.fl_banner)
    FrameLayout flBanner;
    @BindView(R.id.rl_shop_dc_empty)
    RelativeLayout rlShopDcEmpty;

    protected boolean isLogin = false;

    private ShopDetailsActivity activity;
    private ArrayList<GoodscategorylisBean.DataBean> leftData = new ArrayList<>();
    private ArrayList<GoodscategorylisBean.DataBean.GoodsVOListBean> rightData = new ArrayList<>();
    private ShopCategoryAdapter leftAdapter;
    private ShopCategoryGoodItemAdapter rightAdapter;
    private boolean mIsTouchRvRight = false;
    private boolean mIsTouchRvLeft = false;
    PowerfulStickyDecoration decoration;
    private CenterLayoutManager mCenterLayoutManager;
    private RecyclerView.State mRvState = new RecyclerView.State();
    int currentPosition = 0;
    //商品sku
    private ProductSkuDialog dialog;
    private ProductData productData;
    private View mView;
    private View mFootre_view;


    public static Fragment getInstance(ShopDetailsActivity shopDetailsActivity) {
        MenuScrollFragment menuFragment = new MenuScrollFragment();
        menuFragment.activity = shopDetailsActivity;
        return menuFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_menu_scroll;
    }


    @Override
    protected void initView() {
//        MenuRVFragment mMenuRVFragment = new MenuRVFragment(activity);
//        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
//        transaction.replace(R.id.fragment_container, mMenuRVFragment);
//        transaction.commit();
        leftAdapter = new ShopCategoryAdapter(mContext, leftData);
        mCenterLayoutManager = new CenterLayoutManager(mContext);
        rvLeft.setLayoutManager(mCenterLayoutManager);
        rightAdapter = new ShopCategoryGoodItemAdapter(mContext, rightData);
        rvRight.setLayoutManager(new LinearLayoutManager(mContext));
        mView = getLayoutInflater().inflate(R.layout.footer_view, rvRight, false);
        mFootre_view = mView.findViewById(R.id.footer_view);

        mPresenter = new RestaurantShopPresenter();
        mPresenter.attachView(this);
        mPresenter.getGoodscategoryList(activity.tenantId);

        isLogin = SPUtils.getBoolean("ISLOGIN", false);
        //右边 RecyclerView item 点击事件监听
        rightAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_shop_add:
                        LogUtils.e("加入购物车" + isLogin);
                        if (isLogin) {
                            addCart(rightData.get(position), "", "", 1);

                        } else {
                            activity.startActivity(new Intent(activity, LoginActivity.class));
                        }

                        break;
                    case R.id.tv_shop_add://选择规格
                        productData = new ProductData();

                        productData.setPid(rightData.get(position).getId());
                        productData.setGoodsName(rightData.get(position).getGoodsName());
                        productData.setPictureUrl(rightData.get(position).getGoodsImg());
                        productData.setMaxPrice(rightData.get(position).getGoodsPrice());
                        productData.setMinPrice(rightData.get(position).getGoodsPrice());
                        productData.setStockQuantity(rightData.get(position).getInventory());
//                        productData.setSkus(sku);
                        List<Sku> skus = new ArrayList<>();
                        for (int i = 0; i < rightData.get(position).getGoodsSkus().size(); i++) {
                            Sku sku = new Sku();
                            sku.setSid(rightData.get(position).getGoodsSkus().get(i).getId());
                            sku.setPrice(rightData.get(position).getGoodsSkus().get(i).getGoodsPrice());
                            sku.setPictureUrl(rightData.get(position).getGoodsSkus().get(i).getSpecImg());
                            sku.setStockQuantity(rightData.get(position).getGoodsSkus().get(i).getInventory());

                            String[] result = rightData.get(position).getGoodsSkus().get(i).getSpec().split(",");
                            List<SkuAttribute> attributes = new ArrayList<>();
                            for (String s : result) {
                                String str = s.replace("{", "");
                                str = str.replace("}", "");
                                str = str.replace("\"", "");
                                String[] spec = str.split(":");
//                                LogUtils.e("attribute.result:" + s);
//                                LogUtils.e("attribute.setKey:" + spec[0]);
//                                LogUtils.e("attribute.setValue:" + spec[1]);
                                SkuAttribute attribute = new SkuAttribute();
                                attribute.setKey(spec[0]);
                                attribute.setValue(spec[1]);
                                attributes.add(attribute);
                            }
                            sku.setAttributes(attributes);
                            skus.add(sku);
                        }

                        productData.setSkus(skus);
                        showSkuDialog(position);

                        break;
                }
            }
        });

        //左边 RecyclerView item 点击事件监听
        leftAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.rl_left:
                        LogUtils.e(leftData.get(position).getCategoryName());
                        for (int i = 0; i < rightData.size(); i++) {

                            if (leftData.get(position).getCategoryName().equals(rightData.get(i).getCategoryName())) {
                                //右边菜品 RecyclerView 将指定 item 滚动到可见第一条
                                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) rvRight.getLayoutManager();
                                linearLayoutManager.scrollToPositionWithOffset(i, 0);
                                break;
                            }

                        }
                        for (int i = 0; i < leftData.size(); i++) {
                            leftData.get(i).setCheck(false);
                        }
                        leftData.get(position).setCheck(true);
                        leftAdapter.notifyDataSetChanged();
                        break;

                }
            }
        });


//        右边 RecyclerView 滚动监听
        rvRight.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //实现右边滚动联动左边 RecyclerView
                int index = 99;
                LinearLayoutManager layoutManager = (LinearLayoutManager) rvRight.getLayoutManager();
                int position = layoutManager.findFirstCompletelyVisibleItemPosition();
//                LogUtils.e("position:" + position);
                if (position == -1) {
                    position = rightData.size() - 1;
                }
                for (int i = 0; i < leftData.size(); i++) {
//                    LogUtils.e("position1:" + position + "  " + rightAdapter.getData().get(position).getCategoryName());
//                    LogUtils.e("leftData:" + i + "  " + leftData.get(i).getCategoryName());
                    if (leftData.get(i).getCategoryName().equals(rightAdapter.getData().get(position).getCategoryName())) {
                        index = i;
                        leftData.get(i).setCheck(true);
                    } else {
                        leftData.get(i).setCheck(false);
                    }

                }
                if (currentPosition != index) {
//                    LogUtils.e("实现右边滚动联动左边notifyDataSetChanged");
                    leftAdapter.notifyDataSetChanged();
                    mCenterLayoutManager.smoothScrollToPosition(rvLeft, mRvState, index);
                    currentPosition = index;
                }
            }
        });

        //根据屏幕实际宽高设置两个recyclerView高度为固定值
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                rvRight.getLayoutParams().height = scrollView.getHeight();
                rvLeft.getLayoutParams().height = scrollView.getHeight();
                rvRight.setLayoutParams(rvRight.getLayoutParams());
                rvLeft.setLayoutParams(rvLeft.getLayoutParams());
                mFootre_view.getLayoutParams().height = scrollView.getHeight() - PxUtils.dp2px(250);
            }
        });


        //记录是 rv_left 被触摸还是 rv_right 被触摸

        View.OnTouchListener onTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN && v.getId() == R.id.rv_right) {
                    mIsTouchRvRight = true;
                }
                if (event.getAction() == MotionEvent.ACTION_UP && v.getId() == R.id.rv_right) {
                    mIsTouchRvRight = false;
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN && v.getId() == R.id.rv_left) {
                    mIsTouchRvLeft = true;
                }
                if (event.getAction() == MotionEvent.ACTION_UP && v.getId() == R.id.rv_left) {
                    mIsTouchRvLeft = false;
                }

                return false;
            }
        };


        rvRight.setOnTouchListener(onTouchListener);
        rvLeft.setOnTouchListener(onTouchListener);

        //scrollView 滚动监听
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //上滑时，如果 bannerView 尚未被滚出屏幕，则不允许左右两个 RecyclerView 滚动 （通过 offsetChildrenVertical(dy) 实现两个 rv 未滚动的假象）
                int dy = scrollY - oldScrollY;
                LogUtils.e("setOnScrollChangeListener：scrollY" + scrollY);
                LogUtils.e("setOnScrollChangeListener：oldScrollY" + oldScrollY);
                LogUtils.e("setOnScrollChangeListener：dy" + dy);
                LogUtils.e("setOnScrollChangeListener： cvShopMenu.getHeight()" + cvShopMenu.getHeight());
//                if (dy > 0) {
//                    if (scrollY < cvShopMenu.getHeight()) {
//                        if (mIsTouchRvRight) {
//                            rvRight.offsetChildrenVertical(dy);
//                        }
//                        if (mIsTouchRvLeft) {
//                            rvLeft.offsetChildrenVertical(dy);
//                        }
//                    }
//                }
            }
        });


    }

    //添加购物车
    private void addCart(GoodscategorylisBean.DataBean.GoodsVOListBean bean, String goodsSkuId, String goodsSkuSpec, int quantity) {
        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject.put("goodsId", bean.getId());
            jsonObject.put("goodsAmount", quantity);
//            jsonObject.put("goodsAmount", etSearchGoods.getText().toString());
            jsonObject.put("goodsName", bean.getGoodsName());
            jsonObject.put("tenantId", bean.getTenantId());
            jsonObject.put("shopsTypeId", bean.getShopsTypeId());
            jsonObject.put("isSpec", bean.getIsSpec());
            jsonObject.put("status", bean.getStatus());

            if (bean.getIsSpec() == 1) {
                jsonObject.put("goodsSkuId", goodsSkuId);
                jsonObject.put("goodsSkuSpec", goodsSkuSpec);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mPresenter.getAddCartShop(getToken(), Utils.getRequestBody(jsonObject));
    }

    protected String getToken() {
        String aaccessToken = SPUtils.getString(Constant.AaccessToken, null);
        if (TextUtils.isEmpty(aaccessToken)) {
//            ToastUtils.show("token不能空");
            return "";
        }
        return aaccessToken;
    }


    @Override
    protected boolean registerEventBus() {
        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(ReviewTypeCountEvent event) {

        switch (event.getType()) {
            case 1:
                BannerUtils.initBanner(activity.currentShopsInfoBean.getData().getShopsImageList(), banner);
                scrollView.setLooperHeaderHeight(flBanner.getHeight());
                break;

        }

    }

    @Override
    public void getCurrentShopsInfo(CurrentShopsInfoBean bean) {

    }

    @Override
    public void getGoodscategoryList(GoodscategorylisBean bean) {
        if (bean.getData().size() == 0) {
            rlShopDcEmpty.setVisibility(View.VISIBLE);
            llMain.setVisibility(View.GONE);
            flBanner.setVisibility(View.GONE);
        } else {
            rlShopDcEmpty.setVisibility(View.GONE);
            llMain.setVisibility(View.VISIBLE);
            flBanner.setVisibility(View.VISIBLE);

            for (int i = 0; i < bean.getData().size(); i++) {
                for (int j = 0; j < bean.getData().get(i).getGoodsVOList().size(); j++) {
                    bean.getData().get(i).getGoodsVOList().get(j).setCategoryName(bean.getData().get(i).getCategoryName());
                    bean.getData().get(i).getGoodsVOList().get(j).setPic(bean.getData().get(i).getPic());
                }
                if (i == 0) {
                    bean.getData().get(i).setCheck(true);
                } else {
                    bean.getData().get(i).setCheck(false);
                }
                leftData.add(bean.getData().get(i));
                rightData.addAll(bean.getData().get(i).getGoodsVOList());
            }
            LogUtils.e("getGoodscategoryList-rightData" + rightData.size());
//        leftData.addAll(bean.getData());

            rvLeft.setAdapter(leftAdapter);
//        ShopCategoryGoodItemAdapter shopCategoryGoodAdapter = new ShopCategoryGoodItemAdapter(mContext, rightData);

//        rvRight.addItemDecoration(new SectionDecoration(rightData, mContext, new SectionDecoration.DecorationCallback() {
//            @Override
//
//            public String getGroupId(int position) {
//                if (rightData.get(position).getCategoryName() != null) {
//                    return rightData.get(position).getCategoryName();
//                }
//                return "-1";
//            }
//
//            @Override
//            public String getGroupFirstLine(int position) {
//                if (rightData.get(position).getCategoryName() != null) {
//                    return rightData.get(position).getCategoryName();
//                }
//                return "";
//            }
//        }));

            //------------- PowerfulStickyDecoration 使用部分  ----------------
            String img = "https://templatefile.slmykj.com/myfiles/bld/tujian.png";
            decoration = PowerfulStickyDecoration.Builder
                    .init(new PowerGroupListener() {
                        @Override
                        public String getGroupName(int position) {
                            //获取组名，用于判断是否是同一组
                            if (rightData.size() > position) {
                                return rightData.get(position).getCategoryName();
                            }
                            return null;
                        }

                        @Override
                        public View getGroupView(int position) {
                            //获取自定定义的组View
                            if (rightData.size() > position) {
                                final View view = getLayoutInflater().inflate(R.layout.layout_rv_group, null, false);
                                TextView textView = (TextView) view.findViewById(R.id.tv);
                                ImageView imageView = (ImageView) view.findViewById(R.id.iv);
                                if (rightData.get(position).getPic().isEmpty()) {
                                    textView.setText(rightData.get(position).getCategoryName());
                                    imageView.setVisibility(View.GONE);
                                } else {
                                    textView.setVisibility(View.GONE);
                                    Glide.with(mContext)
                                            .load(rightData.get(position).getPic())
                                            .into(new SimpleTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                    //加载完成后的处理
                                                    imageView.setImageDrawable(resource);
                                                    if (decoration != null) {
                                                        decoration.notifyRedraw(rvRight, view, position);
                                                    }
                                                }
                                            });
                                }
                                return view;
                            } else {
                                return null;
                            }
                        }
                    })
                    .setCacheEnable(true)
                    .setGroupHeight(PxUtils.dp2px(59))

                    .build();

            //----------------                 -------------
            rvRight.addItemDecoration(decoration);
            rvRight.setAdapter(rightAdapter);


            rightAdapter.addFooterView(mView);
        }

    }


    @Override
    public void getReviewTypeCount(ReviewTypeCountBean bean) {

    }

    @Override
    public void getShopReviewPage(ShopReviewPageBean bean) {

    }

    @Override
    public void getAddCartShop(CommonDataBean bean) {
        activity.getShopsCart();
    }

    @Override
    public void getShopsCartList(CartBean bean) {

    }

    @Override
    public void getShopCouponreceive(CommonDataBean bean) {

    }

    /**
     * @param position
     * @description 购物车的弹窗方法
     */
    private void showSkuDialog(int position) {
        if (dialog == null) {
            dialog = new ProductSkuDialog(mContext);
            dialog.setData(productData, new ProductSkuDialog.Callback() {
                @Override
                public void onAdded(Sku sku, int quantity) {
                    LogUtils.e("onAdded:" + sku.toString());
                    LogUtils.e("quantity:" + quantity);
                    //立即购买再跳转到
//                    Toast.makeText(mContext, "添加购物车成功 " + sku.toString(), Toast.LENGTH_SHORT).show();
                    if (isLogin) {
                        StringBuffer spec = new StringBuffer();
                        for (SkuAttribute skuAttribute : sku.getAttributes()) {
                            spec.append(skuAttribute.getValue() + ",");
                        }
                        spec.deleteCharAt(spec.length() - 1);
                        addCart(rightData.get(position), sku.getSid(), spec.toString(), quantity);

                    } else {
                        activity.startActivity(new Intent(activity, LoginActivity.class));
                    }

                }

                @Override
                public void onSelect(String selected) {
                    //默认设置 有选的
//                    tv.setText(selected);
//                    LogUtils.e("onSelect:"+selected);
                }

                @Override
                public void reUnSelect() {

                }
            });
        }
        dialog.show();
    }

}
